package com.ThreadSyncEg;
//2个人同一个账号同时取钱 锁实体对象
// 锁应用于一个实体对象
public class BankEg {
    //账户信息
    public static void main(String[] args) throws InterruptedException {
        Account account = new Account(500,"购车基金");

        Drawing My = new Drawing(account,500,"A"); //我取的
        Drawing YourGirl = new Drawing(account,100,"B");
        YourGirl.start();
        My.start();

        Thread.State GirlState = YourGirl.getState();
        Thread.State MyState = My.getState();
        while (GirlState!=Thread.State.TERMINATED||MyState!=Thread.State.TERMINATED){
            Thread.sleep(100);
            MyState = My.getState();
            GirlState = YourGirl.getState();
            //谁是BLOCKED状态意味为下次锁的对象
            System.out.println("A运行状态："+MyState+"|B运行状态："+GirlState);
        }

    }
}
//账号
class Account{
    int money;
    String name;

    public Account(int money, String name) {
        this.money = money;
        this.name = name;
    }
}
//银行 ：模拟取钱
class Drawing extends Thread{
    Account account;//账号对象
    int drawingMoney;//取多少钱
    int nowMoney;//自身的钱

    public Drawing(Account account, int drawingMoney, String name){
        super(name);//调用父类方法参数 理解 生成Thread对象时 name作为名字
        this.account = account;
        this.drawingMoney = drawingMoney;

    }

    //取钱
    @Override
    public void run() {
        //锁对象account 当有线程调用对象时 只允许当前线程使用该对象 线程结束才放出对象 给下一个线程使用
        synchronized (account){
        //判断有钱没
        if(account.money-drawingMoney<0){
            System.out.println(Thread.currentThread().getName()+"准备取"+drawingMoney+",钱不够");
            return;
        }

        //卡内余额
        account.money = account.money-drawingMoney;
        nowMoney = drawingMoney;
        try {
            Thread.sleep(500);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        //this.getName() this.继承Thread类的方法
            System.out.println(this.getName()+"取出->"+nowMoney);
            System.out.println(account.name+"余额为 "+account.money);
        }
    }




}
